import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:refresh_page/src/refresh_ext.dart';

import 'refresh_page_enum.dart';
import 'refresh_page_result.dart';

abstract class RefreshPageController<T> extends GetxController {
  final loadState = LoadState.first.obs;

  ///分页数
  int _page = 1;

  ///数据
  List<T> data = [];

  Object refreshId = Object();

  ///控制器
  final refreshController = RefreshController();

  ///加载成功展示页面
  showSuccess(List<T> data) {
    loadState.value = data.isNotEmpty ? LoadState.success : LoadState.empty;
  }

  ///加载失败展示页面
  showError() {
    loadState.value = LoadState.error;
  }

  ///重新加载
  reload() async {
    loadState.value = LoadState.first;
    await refreshData();
  }

  ///加载更多
  loadMore() async {
    _page++;
    await _requestData(refresh: Refresh.pullUp);
  }

  ///刷新
  refreshData() async {
    _page = 1;
    await _requestData(refresh: Refresh.pullDown);
  }

  @override
  void onInit() async {
    super.onInit();
    await _requestData();
  }

  ///获取数据
  _requestData({
    Refresh refresh = Refresh.first,
  }) async {
    final res = await request(_page);
    if (res.success) {
      RefreshExtension.onSuccess(refreshController, refresh, res.over);
      if (refresh == Refresh.pullDown) {
        this.data.clear();
      }
      this.data.addAll(res.data!);
      showSuccess(data);
      update([refreshId]);
    } else {
      RefreshExtension.onError(refreshController, refresh);
      showError();
    }
  }

  Future<RefreshPageResult<T>> request(int page);
}
